<?php
namespace app\service;

use think\Service;
use EasyWeChat\OfficialAccount\Application;

class Wechat extends Service
{
    private $handle;
    private $sesskey;
    public $openid;

    public $message = '';
    public $state = 200;

    public function __construct()
    {
        $this->handle = new Application(config('wechat'));
        session('?wechat_sesskey') && ($this->sesskey = session('wechat_sesskey'));
        session('?wechat_openid') && ($this->openid = session('wechat_openid'));
        // 将响应输出
        // $response->send();exit; // Laravel 里请使用：return $response;
    }
    /**
     * 登录授权
     *
     * @param string $code
     * @return void
     */
    public function auth(string $code)
    {
        $session = $this->handle->auth->session($code);
        session('wechat_sesskey', $session['session_key']);
        session('wechat_openid', $session['openid']);
        $this->sesskey = $session['session_key'];
        $this->openid = $session['openid'];
        return $session;
    }
    /**
     * 解密
     *
     * @param string $iv
     * @param string $encryptedData
     * @return void
     */
    public function decrypt(string $iv, string $encryptedData){
        return $this->handle->encryptor->decryptData($this->sesskey, $iv, $encryptedData);
    }
    /**
     * 模板消息
     *
     * @param [type] $openid
     * @param [type] $tmpl_id
     * @param array $data
     * @param string $url
     * @return void
     */
    public function send($openid, $tmpl_id, $data=[], $url = ''){
        return $this->handle->template_message->send([
            'touser' => $openid,  // 用户wechat_openid
            'template_id' => $tmpl_id, // 模板ID
            'url' => $url, // 跳转路径
            'miniprogram' => [
                'appid' => config('wechat.mini.app_id'),
                'pagepath' => 'pages/' . $url,
            ],
            'data' => $data
        ]);
    }
    // 小程序码
    public function qrcode(string $path, array $optional = []){
        return $this->handle->app_code->get($path, $optional);
    }
    /**
     * 订阅消息
     *
     * @param [type] $template_id
     * @param [type] $touser
     * @param [type] $page
     * @param array $params
     * @return void
     */ 
    public function subscribe($template_id, $touser, $page, $params = []){
        $data = [
            'template_id' => $template_id, // 所需下发的订阅模板id
            'touser' => $touser,     // 接收者（用户）的 wechat_openid
            'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => []
        ];
        foreach($params as $key => $val){
            $data['data'][$key] = ['value' => $val];
        }
        return $this->handle->subscribe_message->send($data);    
    }
}
